package cn.xd.base.persistence.repository.impl;


import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.xd.base.basic.type.*;
import cn.xd.base.domain.entity.AdminOrg;
import cn.xd.base.domain.entity.AdminOrgRole;
import cn.xd.base.domain.entity.AdminUserOrgRole;
import cn.xd.base.domain.repository.AdminOrgRepository;
import cn.xd.base.persistence.dos.*;
import cn.xd.base.persistence.mps.AdminOrgMpService;
import cn.xd.base.persistence.mps.AdminOrgRoleMpService;
import cn.xd.base.persistence.mps.AdminUserMpService;
import cn.xd.base.persistence.mps.AdminUserOrgRoleMpService;
import cn.xd.common.exception.BizException;
import cn.xd.core.basic.common.CreateTime;
import cn.xd.core.ddd.db.DbRepositorySupport;
import cn.xd.core.ddd.diff.EntityDiff;
import cn.xd.core.response.ObjectResult;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

@Repository
public class AdminOrgRepositoryImpl extends DbRepositorySupport<AdminOrg, AdminOrgId> implements AdminOrgRepository {
    @Resource
    private AdminOrgMpService adminOrgMpService;
    @Resource
    private AdminUserMpService adminUserMpService;
    @Resource
    private AdminOrgRoleMpService adminOrgRoleMpService;
    @Resource
    private AdminUserOrgRoleMpService adminUserOrgRoleMpService;

    @Override
    protected void onInsert(AdminOrg aggregate) {
        adminOrgMpService.getAdminOrg(aggregate.getName().getValue(), aggregate.getParentId().getValue(), null).isNotEmptyThrow("存在同级并同名的机构");
        if (ObjUtil.isNotEmpty(aggregate.getUserId().getValue())) {
            AdminUserDO adminUserDO = adminUserMpService.getResult(aggregate.getUserId()).isEmptyThrow("未找到该admin用户");
            if (ObjUtil.isEmpty(adminUserDO.getGlobalUserId())) {
                throw new BizException("未找到该admin用户对应的app用户，请先绑定");
            }
            addUserOrgRole(aggregate);
        }
        AdminOrgDO adminOrg = adminOrgMpService.getResult(aggregate.getParentId()).isEmptyThrow("上级机构不存在");
        aggregate.setPath(Path.of(adminOrg.getPath() + aggregate.getId().getValue() + "/"));
        adminOrgMpService.saveResult(aggregate, AdminOrgConverter.INSTANCE).failThrow();
    }

    @Override
    protected AdminOrg onSelect(AdminOrgId id) {
        return adminOrgMpService.getResult(id, AdminOrgConverter.INSTANCE).get();
    }

    @Override
    protected void onUpdate(AdminOrg aggregate, EntityDiff diff) {
        if (diff.isSelfModified()) {
            AdminOrgDO bean = diff.getBean(AdminOrgDO.class);
            if (bean.getId().equals(0L)) {
                throw new BizException("总公司不能修改");
            }
            if (StrUtil.isNotBlank(bean.getName())) {
                adminOrgMpService.getAdminOrg(aggregate.getName().getValue(), aggregate.getParentId().getValue(), aggregate.getId().getValue()).isNotEmptyThrow("存在同级并同名的机构");
            }
            if (ObjUtil.isNotNull(bean.getUserId()) && !bean.getUserId().equals(aggregate.getUserId().getValue())) {
                AdminUserDO adminUserDO = adminUserMpService.getResult(bean.getUserId()).isEmptyThrow("未找到该admin用户");
                if (ObjUtil.isEmpty(adminUserDO.getGlobalUserId())) {
                    throw new BizException("未找到该admin用户对应的app用户，请先绑定");
                }
                ObjectResult<AdminOrgRoleDO> adminOrgRoleDOObjectResult = adminOrgRoleMpService.getOneForLimitOneResult(Wrappers.lambdaQuery(AdminOrgRoleDO.class).eq(AdminOrgRoleDO::getOrgId, aggregate.getId())
                        .eq(AdminOrgRoleDO::getRoleId, 0L));
                adminOrgRoleDOObjectResult.isNotEmpty(item -> {
                    adminUserOrgRoleMpService.remove(Wrappers.lambdaQuery(AdminUserOrgRoleDO.class)
                                    .eq(AdminUserOrgRoleDO::getOrgRoleId,item.getId()));
                    adminUserOrgRoleMpService.saveResult(AdminUserOrgRole.builder().userId(aggregate.getUserId())
                            .orgRoleId(AdminOrgRoleId.of(item.getId())).creatorId(aggregate.getCreatorId()).createTime(CreateTime.now())
                            .build(), AdminUserOrgRoleConverter.INSTANCE);
                });
                adminOrgRoleDOObjectResult.isEmpty(() -> {
                    addUserOrgRole(aggregate);
                });
            }
            if (ObjUtil.isNotNull(bean.getParentId())) {
                AdminOrgDO adminOrg = adminOrgMpService.getResult(aggregate.getParentId()).isEmptyThrow("上级机构不存在");
                bean.setPath(adminOrg.getPath() + aggregate.getId().getValue() + "/");
            }
            adminOrgMpService.updateResult(bean);
        }
    }

    private void addUserOrgRole(AdminOrg aggregate) {
        adminOrgRoleMpService.saveResult(AdminOrgRole.builder().orgId(aggregate.getId()).roleId(AdminRoleId.of(0L))
                .creatorId(aggregate.getCreatorId()).createTime(CreateTime.now()).build(), AdminOrgRoleConverter.INSTANCE).success(item -> {
            adminUserOrgRoleMpService.saveResult(AdminUserOrgRole.builder().userId(aggregate.getUserId())
                    .orgRoleId(AdminOrgRoleId.of(item.getId())).creatorId(aggregate.getCreatorId()).createTime(CreateTime.now())
                    .build(), AdminUserOrgRoleConverter.INSTANCE);
        });
    }

    @Override
    protected void onDelete(AdminOrg aggregate) {
        if (aggregate.getId().getValue().equals(0L)) {
            throw new BizException("总公司不能删除");
        }
        aggregate.delete();
        AdminOrgDO adminOrgDO = AdminOrgConverter.INSTANCE.toData(aggregate);
        adminOrgMpService.updateResult(adminOrgDO);
    }

}
